package com.example.im.ui.adapter

import android.content.Context
import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.im.R
import com.example.im.bean.UserRoom
import com.xlkj.ehobe.storage.ui.adapter.holder.RecyclerViewHolder
import kotlinx.android.synthetic.main.recycler_item_room_owner.view.*
import java.util.ArrayList


class RoomOwnerAdapter(

    private val mContext: Context,
    private val userRooms: MutableList<UserRoom>,
    private val isOwner: Boolean
) :
    RecyclerView.Adapter<RecyclerViewHolder>() {

    private val sbArray = SparseBooleanArray()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(mContext).inflate(
                R.layout.recycler_item_room_owner, parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {

        val view: View = holder.itemView
        if (isOwner) {
            view.check_box.visibility = View.VISIBLE
        } else {
            view.check_box.visibility = View.GONE
        }
        view.tv_name.text = userRooms[position].nickname
        view.check_box.isChecked = isItemChecked(position)
        view.check_box.setOnClickListener {
            if (isItemChecked(position)) {
                setItemChecked(position, false)
            } else {
                setItemChecked(position, true)
            }
        }
        view.setOnClickListener {
            if (isItemChecked(position)) {
                setItemChecked(position, false)
            } else {
                setItemChecked(position, true)
            }
            notifyItemChanged(position)
        }
        view.tag = position
    }

    override fun getItemCount(): Int {
        return userRooms.size
    }

    fun addData(userRooms: MutableList<UserRoom>) {
        this.userRooms.clear()
        this.userRooms.addAll(userRooms)
        this.notifyDataSetChanged()
    }

    //设置给定位置条目的选择状态
    private fun setItemChecked(position: Int, isChecked: Boolean) {
        sbArray.put(position, isChecked)
    }

    //根据位置判断条目是否选中
    private fun isItemChecked(position: Int): Boolean {
        return sbArray.get(position)
    }

    //获得选中条目的结果
    fun getSelectedItem(): ArrayList<UserRoom> {
        val selectList = ArrayList<UserRoom>()
        for (i in 0 until userRooms.size) {
            if (isItemChecked(i)) {
                selectList.add(userRooms[i])
            }
        }
        return selectList
    }

}
